package com.lebron.kotlin.ui.activity

import android.os.Build
import android.os.Bundle
import android.support.v4.app.FragmentTransaction
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatDelegate
import android.support.v7.widget.SwitchCompat
import android.support.v7.widget.Toolbar
import android.transition.Fade
import android.view.MenuItem
import android.widget.TextView
import com.lebron.kotlin.BuildConfig
import com.lebron.kotlin.R
import com.lebron.kotlin.map.LocationManager
import com.lebron.kotlin.ui.fragment.BookFragment
import com.lebron.kotlin.ui.fragment.HomeFragment
import com.lebron.kotlin.ui.fragment.MovieFragment
import com.lebron.kotlin.ui.fragment.MusicFragment
import com.lebron.kotlin.ui.helper.BottomNavigationHelper
import com.lebron.kotlin.utils.AppManager.exitApp
import com.lebron.kotlin.utils.AppManager.isDoubleClickExit
import com.lebron.kotlin.utils.ToastUtil.toast
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : BaseActivity() {


    private var movieFragment: MovieFragment? = null
    private var homeFragment: HomeFragment? = null
    private var musicFragment: MusicFragment? = null
    private var bookFragment: BookFragment? = null

    private var currentTabId: Int = 1

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    private val location = LocationManager()

    override fun onCreate(savedInstanceState: Bundle?) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val fade = Fade()
            fade.duration = 1000
            window.enterTransition = fade
        }
        super.onCreate(savedInstanceState)

        if (savedInstanceState != null) {
            homeFragment = supportFragmentManager.findFragmentByTag(HomeFragment::class.java.simpleName) as HomeFragment
            movieFragment = supportFragmentManager.findFragmentByTag(MovieFragment::class.java.simpleName) as MovieFragment
            bookFragment = supportFragmentManager.findFragmentByTag(BookFragment::class.java.simpleName) as BookFragment
            musicFragment = supportFragmentManager.findFragmentByTag(MusicFragment::class.java.simpleName) as MusicFragment
            changeTabFragment()
        } else {
            homeFragment = HomeFragment()
            movieFragment = MovieFragment()
            bookFragment = BookFragment()
            musicFragment = MusicFragment()
            supportFragmentManager.beginTransaction().add(R.id.frame_layout, homeFragment, HomeFragment::class.java.simpleName).hide(homeFragment).addToBackStack(null)
                    .add(R.id.frame_layout, movieFragment, MovieFragment::class.java.simpleName).hide(movieFragment).addToBackStack(null)
                    .add(R.id.frame_layout, bookFragment, BookFragment::class.java.simpleName).hide(bookFragment).addToBackStack(null)
                    .add(R.id.frame_layout, musicFragment, MusicFragment::class.java.simpleName).hide(musicFragment).addToBackStack(null)
                    .show(movieFragment)
                    .commitAllowingStateLoss()
        }

    }


    private fun changeTabFragment() {
        val fragmentTransition = supportFragmentManager.beginTransaction()
        hideAllFragment(fragmentTransition)
        when (currentTabId) {
        //首页
            0 -> {
                currentTabId = 0
                if (null == homeFragment) {
                    homeFragment = HomeFragment()
                    fragmentTransition.add(R.id.frame_layout, homeFragment, HomeFragment::class.java.simpleName)
                            .addToBackStack(null)
                } else {
                    fragmentTransition.show(homeFragment)
                }
            }
        //电影界面
            1 -> {
                currentTabId = 1
                if (null == movieFragment) {
                    movieFragment = MovieFragment()
                    fragmentTransition.add(R.id.frame_layout, movieFragment, MovieFragment::class.java.simpleName)
                            .addToBackStack(null)
                } else {
                    fragmentTransition.show(movieFragment)
                }
            }
        //书籍界面
            2 -> {
                currentTabId = 2
                if (null == bookFragment) {
                    bookFragment = BookFragment()
                    fragmentTransition.add(R.id.frame_layout, bookFragment, BookFragment::class.java.simpleName)
                            .addToBackStack(null)
                } else {
                    fragmentTransition.show(bookFragment)
                }
            }
        //音乐界面
            3 -> {
                currentTabId = 3
                if (null == musicFragment) {
                    musicFragment = MusicFragment()
                    fragmentTransition.add(R.id.frame_layout, musicFragment, MusicFragment::class.java.simpleName)
                            .addToBackStack(null)
                } else {
                    fragmentTransition.show(musicFragment)
                }
            }
        }
        fragmentTransition.commitAllowingStateLoss()
    }

    /**
     * 隐藏所有fragment
     */
    private fun hideAllFragment(transaction: FragmentTransaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment)
        }
        if (movieFragment != null) {
            transaction.hide(movieFragment)
        }
        if (bookFragment != null) {
            transaction.hide(bookFragment)
        }
        if (musicFragment != null) {
            transaction.hide(musicFragment)
        }

    }

    override fun initData() {
        //定位
        location.startLocation()
        location.initLocation(this)
                //设置定位回调监听
                ?.setLocationListener { aMapLocation ->
                    if (aMapLocation.errorCode == 0) {//有数据
                    } else {//报错
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    }

                }
    }

    override fun initView() {

        initDrawerLayout()
        initBottomView()

    }

    private fun initDrawerLayout() {
//        navigation_view.setItemBackgroundResource(R.color.colorPrimary)
        //这是获取actionLayout中组件的方法
        val versionText = navigation_view.menu.getItem(3).actionView.findViewById<TextView>(R.id.menu_text)
        versionText.text = BuildConfig.VERSION_NAME
        versionText.setOnClickListener { toast("当前是最新版本") }
        navigation_view.setCheckedItem(R.id.nav_item2)
        navigation_view.setNavigationItemSelectedListener { item: MenuItem ->
            when (item.itemId) {
                R.id.nav_item1 -> {
                    toast("item1")
                }
                R.id.nav_item2 -> {
                    toast("item2")
                }
                R.id.nav_item3 -> {
                    toast("item3")
                }
                R.id.nav_item_version -> {
                    toast("当前版本：" + BuildConfig.VERSION_NAME)

                }
            }
            true
        }
        //设置日间夜间模式
        val themeSwitch: SwitchCompat = navigation_view.menu.getItem(0).actionView.findViewById(R.id.view_switch)
        themeSwitch.setOnCheckedChangeListener { _, isChecked ->
            themeSwitch.isChecked = isChecked
            if (isChecked) {
                delegate.setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES)
            } else {
                delegate.setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO)
            }
        }
    }

    /**
     * 底部导航组件设置
     */
    private fun initBottomView() {
        BottomNavigationHelper.disableShiftMode(bottom_navigation)
        bottom_navigation.selectedItemId = R.id.menu_movie
        bottom_navigation.setOnNavigationItemSelectedListener { item: MenuItem ->
            when (item.itemId) {
                R.id.menu_home -> {
                    currentTabId = 0
                    changeTabFragment()
                }
                R.id.menu_movie -> {
                    currentTabId = 1
                    changeTabFragment()
                }
                R.id.menu_book -> {
                    currentTabId = 2
                    changeTabFragment()
                }
                R.id.menu_music -> {
                    currentTabId = 3
                    changeTabFragment()
                }
            }
            true
        }
    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawers()
        } else {

            if (isDoubleClickExit()) {
                exitApp()
            } else toast(getString(R.string.home_exit))
        }
    }

    override fun onStop() {
        super.onStop()
        location.stopLocation()
    }

    override fun onDestroy() {
        super.onDestroy()

        location.destroy()
    }

    fun setTool(toolbar: Toolbar) {
        val toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, 0, 0)
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()
    }
}
